package org.example.hospital_frontend.controller;

import org.example.hospital_frontend.common.Result;
import org.example.hospital_frontend.domain.User;
import org.example.hospital_frontend.domain.UserUpdateRequest;
import org.example.hospital_frontend.service.UserService;
import org.example.hospital_frontend.service.UserUpdateRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user/updateRequest")
public class UserUpdateRequestController {

    @Autowired
    private UserUpdateRequestService updateRequestService;
    @Autowired
    private UserService userService;

    // 用户发起修改申请
    @PostMapping("/apply")
    public Result applyUpdate(@RequestBody Map<String, String> req, HttpServletRequest request) {
        User currentUser = (User) request.getSession().getAttribute("USER_LOGIN_STATE");
        if (currentUser == null) return Result.error("未登录");
        String field = req.get("field");
        String newValue = req.get("newValue");
        if (!"history".equals(field) && !"allergy".equals(field)) return Result.error("字段非法");
        if (newValue == null) return Result.error("新值不能为空");

        String oldValue = "history".equals(field) ? currentUser.getHistory() : currentUser.getAllergy();

        UserUpdateRequest updateRequest = new UserUpdateRequest();
        updateRequest.setUserId(currentUser.getId());
        updateRequest.setFieldName(field);
        updateRequest.setOldValue(oldValue);
        updateRequest.setNewValue(newValue);
        updateRequest.setStatus(0);
        updateRequestService.save(updateRequest);
        return Result.success();
    }
}